﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using BluePig.WebApi.Models;

namespace BluePig.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WordsController : ControllerBase
    {
        private readonly BluePigContext _context;

        public WordsController(BluePigContext context)
        {
            _context = context;
        }

        // GET: api/Words
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Word>>> GetWords()
        {
            var list = await _context.Words.ToListAsync();
            return RandomSort(list);
        }
        private List<T> RandomSort<T>(List<T> list)
        {
            var random = new Random();
            var newList = new List<T>();
            foreach (var item in list)
            {
                newList.Insert(random.Next(newList.Count), item);
            }
            return newList;
        }
        // GET: api/Words/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Word>> GetWord(int id)
        {
            var word = await _context.Words.FindAsync(id);

            if (word == null)
            {
                return NotFound();
            }

            return word;
        }

        // PUT: api/Words/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutWord(int id, Word word)
        {
            if (id != word.Id)
            {
                return BadRequest();
            }

            _context.Entry(word).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WordExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        [HttpPost("Async")]
        public async Task<IActionResult> PutAllWord()
        {
            var words = System.IO.File.ReadAllLines(@"C:\Mp4s\words.txt").ToList();
            words.ForEach(r =>
            {
                var cn = "";
                var cnPath = $@"C:\Mp4s\{r}\cn.txt";
                if (System.IO.File.Exists(cnPath))
                    cn = System.IO.File.ReadAllText(cnPath);
                var haveMp4 = System.IO.File.Exists($@"C:\Mp4s\{r}\{r}.mp4");
                var lines = "";
                var lineName = "";
                if (Directory.Exists($@"C:\Mp4s\{r}\ts"))
                {
                    var linePaths = Directory.GetFiles($@"C:\Mp4s\{r}\ts", "*.vtt");
                    var linePath = linePaths.FirstOrDefault();
                    if (System.IO.File.Exists(linePath))
                    {
                        var f = new FileInfo(linePath);
                        lines = System.IO.File.ReadAllText(linePath);
                        lineName = f.Name;
                    }
                }
                _context.Words.Add(new Word()
                {
                    En = r,
                    Cn = cn,
                    HaveMp4 = haveMp4,
                    Lines = lines,
                    LineName = lineName
                });
            });
            await _context.SaveChangesAsync();
            return NoContent();
        }

        // POST: api/Words
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<Word>> PostWord(Word word)
        {
            _context.Words.Add(word);
            await _context.SaveChangesAsync();

             CreatedAtAction("GetWord", new { id = word.Id }, word);
             return Ok();
        }

        // DELETE: api/Words/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteWord(int id)
        {
            var word = await _context.Words.FindAsync(id);
            if (word == null)
            {
                return NotFound();
            }

            _context.Words.Remove(word);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool WordExists(int id)
        {
            return _context.Words.Any(e => e.Id == id);
        }
    }
}
